package com.hctforgreen.greenservice;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import cn.dns.reader.network.BookDownloaderServiceConnection;
import cn.dns.reader.network.VideoDownloaderService;

import com.hctforgreen.greenservice.db.DBVideoDownloadManager;
import com.hctforgreen.greenservice.model.VideoTypeEntity.VideoDetailEntity.VideoPartEntity;
import com.hctforgreen.greenservice.ui.adapter.VideoDownloadAdapter;
import com.hctforgreen.greenservice.ui.widget.PullToRefreshListView;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.ThemeStoreUtil;

/**
 * 视频下载
 * 
 * @author denghb
 * 
 */
public class VideoDownloadActivity extends ParentActivity {
	private DownloadUpdateReceiver mUpdateReceiver;
	private DownloadDownReceiver downloadSucReceiver;
	private VideoDownloadAdapter mAdapter;
	private long mLExitTime = 0;
	private final long mLDelayTime = 2000;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_video_history);
		initSkinLayout();
		initTitleButtonBar();
		initDataAndWindow();
		initDownloadUpdateReceiver();
		initDownloadSucReceiver();
		bindDownloadService();
	}

	private BookDownloaderServiceConnection connection = new BookDownloaderServiceConnection();

	public BookDownloaderServiceConnection getConnection() {
		return connection;
	}

	private void initDataAndWindow() {
		final View convertView = findViewById(R.id.lyt_parent);
		final PullToRefreshListView listView = (PullToRefreshListView) convertView
				.findViewById(R.id.lst_default_list);
		final View loadView = convertView
				.findViewById(R.id.lyt_default_list_load);

		final Handler handler = new Handler() {
			@Override
			public void dispatchMessage(Message msg) {
				switch (msg.what) {

				case HctConstants.STATUS_FAILD:

					List<VideoPartEntity> data = new ArrayList<VideoPartEntity>();
					listView.setAdapter(new VideoDownloadAdapter(
							VideoDownloadActivity.this, data, listView));
					break;
				case HctConstants.STATUS_SUCCESS:
					List<VideoPartEntity> partEntities = (List<VideoPartEntity>) msg.obj;

					if (partEntities != null && !partEntities.isEmpty()) {
						mAdapter = new VideoDownloadAdapter(
								VideoDownloadActivity.this, partEntities,
								listView);
						listView.setAdapter(mAdapter);
					}
					break;

				default:
					break;
				}
				loadView.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				super.dispatchMessage(msg);
			}
		};

		loadView.setVisibility(View.VISIBLE);
		new Thread() {
			public void run() {
				try {
					DBVideoDownloadManager dbVideoManager = new DBVideoDownloadManager(
							getApplicationContext());
					List<VideoPartEntity> partEntities = dbVideoManager
							.queryAll();

					handler.sendMessage(handler.obtainMessage(
							HctConstants.STATUS_SUCCESS, partEntities));
				} catch (Exception e) {
					handler.sendEmptyMessage(HctConstants.STATUS_FAILD);
					e.printStackTrace();
				}

			};
		}.start();

	}

	private void initDownloadUpdateReceiver() {
		/**
		 * 注册下载进度条的监听,在BookShelfAdapter中实现
		 */
		mUpdateReceiver = new DownloadUpdateReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(HctConstants.RECEIVER_VIDEOSHELF_ACTIVITY_DOWNLOAD_UPDATE);
		registerReceiver(mUpdateReceiver, filter);
	}


	private void initTitleButtonBar() {

		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		titleTv.setText(getString(R.string.video_downloader_title));

		final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

	}

	@Override
	public void onBackPressed() {

		super.onBackPressed();
	}

	private void initDownloadSucReceiver() {
		/**
		 * 注册下载进度条的监听,在BookShelfAdapter中实现
		 */
		downloadSucReceiver = new DownloadDownReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(HctConstants.RECEIVER_VIDEOSHELF_ACTIVITY_DOWNLOAD_UPDATE_PARTS);
		registerReceiver(downloadSucReceiver, filter);
	}

	public class DownloadDownReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (mAdapter != null) {
				mAdapter.notifyDataSetChanged();
			}
		}
	}

	public class DownloadUpdateReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String id = intent
					.getStringExtra(HctConstants.ON_DOWNLOAD_SERIVE_KEY_DOWNLOAD_URL);// videoPartEntity's
																						// id
			int progress = intent.getIntExtra(
					HctConstants.ON_DOWNLOAD_SERIVE_KEY_PROGRESS, 0);
			// ON_DOWNLOAD_SERIVE_KEY_PROGRESS
			boolean bSwitchDownloadState = intent.getBooleanExtra(
					HctConstants.ON_DOWNLOAD_SERIVE_KEY_SWITCH_DOWNLOAD_STATE,
					false);

			if (bSwitchDownloadState) {
				mAdapter.updateVideosLayout(id, progress);
				return;
			}
			if (!bSwitchDownloadState
					&& ((System.currentTimeMillis() - mLExitTime) > mLDelayTime)) {
				mLExitTime = System.currentTimeMillis();
				mAdapter.updateVideosLayout(id, progress);
			}
		}
	}

	private void bindDownloadService() {
		final Intent intent = new Intent();
		intent.setClass(VideoDownloadActivity.this,
				VideoDownloaderService.class);

		bindService(intent, connection, Activity.BIND_AUTO_CREATE);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mUpdateReceiver);
		unregisterReceiver(downloadSucReceiver);
		unbindService(connection);
	}

}
